# -*- coding: utf-8 -*-

from django.db import models
from core.models import CoreModel, table_prefix
import reversion

"""报文类型"""


class PacketType(CoreModel):
    product = models.ForeignKey(
        to="pms.Product",
        related_name="packet_type_set",
        on_delete=models.CASCADE,
        db_constraint=False,
        verbose_name="所属产品",
    )
    name = models.CharField(max_length=128, verbose_name="业务报文")
    desc = models.CharField(
        null=True, blank=True, max_length=256, verbose_name="报文描述"
    )

    def __str__(self) -> str:
        return self.name

    class Meta:
        unique_together = (("product", "name"),)
        db_table = table_prefix + "rms_packet_type"
        verbose_name = "报文类型"
        verbose_name_plural = verbose_name
        ordering = ("-update_time",)


"""协议字段"""


@reversion.register()
class PacketField(CoreModel):
    product = models.ForeignKey(
        to="pms.Product",
        related_name="packet_field_set",
        on_delete=models.CASCADE,
        db_constraint=False,
        verbose_name="所属产品",
    )
    packet = models.ForeignKey(
        to="PacketType",
        related_name="packet_field_set",
        on_delete=models.CASCADE,
        db_constraint=False,
        verbose_name="报文名称",
    )
    name = models.CharField(max_length=128, verbose_name="字段名称")
    type = models.CharField(
        null=True, blank=True, max_length=256, verbose_name="字段类型"
    )
    length = models.IntegerField(null=True, blank=True, verbose_name="字段长度")
    desc = models.CharField(
        null=True, blank=True, max_length=256, verbose_name="字段描述"
    )

    def __str__(self) -> str:
        return self.name

    class Meta:
        unique_together = (("product", "packet", "name"),)
        db_table = table_prefix + "rms_packet_field"
        verbose_name = "报文字段"
        verbose_name_plural = verbose_name
        ordering = ("-update_time",)
